using System;
using System.Runtime.InteropServices;
using System.Text;

namespace RawRestructure.Models.DataStructures;

/// <summary>
/// 基础图像保存路径结构体
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 2)]
public struct LastRawSavePath
{
    /// <summary>
    /// 保存的图片队列起始值
    /// </summary>
    public ushort rawNumStart;

    /// <summary>
    /// 保存的张数
    /// </summary>
    public ushort rawLength;

    /// <summary>
    /// 是否为组保存
    /// </summary>
    [MarshalAs(UnmanagedType.U1)]
    public bool rawPair;

    /// <summary>
    /// 保存的文件夹名称（16字节）
    /// </summary>
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public byte[] dirName;

    /// <summary>
    /// 创建LastRawSavePath实例
    /// </summary>
    /// <param name="startIndex">起始索引</param>
    /// <param name="length">长度</param>
    /// <param name="isPair">是否为组保存</param>
    /// <param name="directoryName">目录名称</param>
    /// <returns>LastRawSavePath实例</returns>
    public static LastRawSavePath Create(ushort startIndex, ushort length, bool isPair, string directoryName)
    {
        var result = new LastRawSavePath
        {
            rawNumStart = startIndex,
            rawLength = length,
            rawPair = isPair,
            dirName = new byte[16]
        };

        // 将目录名称转换为字节数组，最大16字节
        var nameBytes = Encoding.UTF8.GetBytes(directoryName);
        var copyLength = Math.Min(nameBytes.Length, 16); // 保留一个字节用于null终止符
        
        Array.Copy(nameBytes, result.dirName, copyLength);
        //result.dirName[15] = 0; // 确保null终止

        return result;
    }

    /// <summary>
    /// 获取目录名称字符串
    /// </summary>
    /// <returns>目录名称</returns>
    public readonly string GetDirectoryName()
    {
        if (dirName == null)
            return string.Empty;

        // 找到null终止符位置
        int nullIndex = Array.IndexOf(dirName, (byte)0);
        int length = nullIndex >= 0 ? nullIndex : dirName.Length;

        return Encoding.UTF8.GetString(dirName, 0, length);
    }

    /// <summary>
    /// 转换为字节数组（小端序）
    /// </summary>
    /// <returns>字节数组</returns>
    public readonly byte[] ToByteArray()
    {
        byte[] result = new byte[21]; // 2 + 2 + 1 + 16 = 21字节
        int offset = 0;
        
        // rawNumStart (ushort, 小端序)
        result[offset++] = (byte)(rawNumStart & 0xFF);
        result[offset++] = (byte)((rawNumStart >> 8) & 0xFF);
        
        // rawLength (ushort, 小端序)
        result[offset++] = (byte)(rawLength & 0xFF);
        result[offset++] = (byte)((rawLength >> 8) & 0xFF);
        
        // rawPair (bool, 1字节)
        result[offset++] = (byte)(rawPair ? 1 : 0);
        
        // dirName (16字节)
        if (dirName != null)
        {
            Array.Copy(dirName, 0, result, offset, Math.Min(dirName.Length, 16));
        }
        
        return result;
    }

    /// <summary>
    /// 从字节数组创建结构体
    /// </summary>
    /// <param name="data">字节数组</param>
    /// <returns>LastRawSavePath实例</returns>
    public static LastRawSavePath FromByteArray(byte[] data)
    {
        int size = Marshal.SizeOf<LastRawSavePath>();
        if (data.Length < size)
            throw new ArgumentException($"数据长度不足，需要{size}字节，实际{data.Length}字节");

        IntPtr ptr = Marshal.AllocHGlobal(size);
        try
        {
            Marshal.Copy(data, 0, ptr, size);
            return Marshal.PtrToStructure<LastRawSavePath>(ptr);
        }
        finally
        {
            Marshal.FreeHGlobal(ptr);
        }
    }
} 